/**
 *  @author Ion Morozan
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.dddforandroid.database.local;

import java.text.ParseException;

import org.apache.http.impl.client.DefaultHttpClient;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.widget.Toast;

import com.dddforandroid.database.server.NotePad.Notes;
import com.dddforandroid.database.server.SyncServerDatabase;
import com.dddforandroid.design.TasksArrayAdapter;

public class DeleteNote extends AsyncTask<Void, Void, String> {

	/* The EditTexts for name, note and date */
	private final String nameET, noteET;
	/* The Context of the application */
	Context mainActivity;
	/* The ServerDatabase object, used for synchronizing the server database */
	private SyncServerDatabase nosql;

	private final String noteID;

	public DefaultHttpClient authClient = new DefaultHttpClient();

	/**
	 * Constructor used for the DeleteNote class
	 * 
	 * @param nameET
	 *            Name EditText
	 * @param noteET
	 *            Note EditText
	 * @param dateET
	 *            Date EditText
	 * @param mainActivity
	 *            The Context of the application
	 * @param nosql
	 *            The ServerDatabase object
	 */
	public DeleteNote(String nameET, String noteET, String id,
			Context mainActivity, SyncServerDatabase nosql,
			DefaultHttpClient http_client) {
		this.noteID = id;
		this.nameET = nameET;
		this.noteET = noteET;
		this.mainActivity = mainActivity;
		this.nosql = nosql;
		this.authClient = http_client;
	}
	/**
	 * What the new thread is supposed to do in background - delete a Note which
	 * already is in the database
	 */
	@Override
	protected String doInBackground(Void... params) {

		String name = nameET;
		String note = noteET;
		String deleteResponse = null;

		Uri deleteUri = Uri.parse(Notes.CONTENT_URI.toString());
		String deleteId;
		try {
			deleteId = getDeletedNoteId(name, note);

			if (mainActivity.getContentResolver().delete(deleteUri,
					Notes._ID + " = '" + noteID + "'"// + " AND " + Note.NOTE
							// + " = '" + note + "'"
					, null) != 0) {
				deleteResponse = deleteServerDB(deleteId);
			}

			return deleteResponse;
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * Invoked after the background computation finishes. The result of the
	 * background computation is passed to this step as a parameter.
	 */
	protected void onPostExecute(String result) {
		if (result != null ) {
			String name = nameET;
			String note = noteET;

			Toast.makeText(
					mainActivity,
					"Deleted the note with name: " + name
							+ " and description: " + note, Toast.LENGTH_SHORT)
					.show();

		} else {
			// TODO error - the name or the note were not correct
		}

	}


	/**
	 * Method used to synchronize the databases after a note was deleted from
	 * the local database
	 * 
	 * @param deletedNote
	 *            The note deleted from the local database
	 * @return The response got from the server after calling HttpDelete method
	 */
	private String deleteServerDB(String deleteId) {

		String deleteResponse = nosql.deleteData(deleteId, authClient);

		return deleteResponse;
	}

	/**
	 * Method used to get all the fields of an Note object, when we only know
	 * the name and the description. This method is needed for synchronizing the
	 * databases when modifying or deleting a Note.
	 * 
	 * @param name
	 *            The name of the modified Note
	 * @param note
	 *            The description of the modified Note
	 * @return The whole Note
	 * @throws ParseException
	 */
	private String getDeletedNoteId(String name, String note)
			throws ParseException {
		ContentResolver provider = mainActivity.getContentResolver();
		/*
		 * Find the information about the updated note - the ID is needed for
		 * the PUT and DELETE methods
		 */
		String deleteId = null;

		String[] projection = new String[] { Notes._ID, Notes.TITLE,
				Notes.NOTE, Notes.CREATED_DATE };
		Uri queryUri = Notes.CONTENT_URI;
		/* Create a query */
		Cursor mCur = provider.query(queryUri, projection, Notes.TITLE + " = '"
				+ name + "'"// + " AND " + Note.NOTE + " = '" + note + "'"
		, null, null);

		if (mCur.moveToFirst()) {
			deleteId = getCurrentNote(mCur);
		}

		mCur.close();
		return deleteId;
	}

	/**
	 * Method used to initialize a new Note object with the current Strings from
	 * the database
	 * 
	 * @param mCur
	 *            The cursor used to move through the query results
	 * @return The Note object newly initialized
	 * @throws ParseException
	 */
	private String getCurrentNote(Cursor mCur) throws ParseException {

		return mCur.getString(mCur.getColumnIndex(Notes._ID));
	}
}
